import { uuid } from '../utils'
import { emptyStyle, getStyle } from '../utils/style'
const updateOutput = (data: any, output: any) => {
  output.get()?.forEach?.((item: any) => {
    const style = data.styleList?.find(({ key }) => key == item.id)
    if (!style) {
      output.remove(item.id)
    } else {
      item.setTitle(style.name)
    }
  })
  data.styleList?.forEach?.((style, idx) => {
    const { key, name } = style
    if (!output.get(key)) {
      const addOption = {
        id: key,
        title: name || `样式${idx + 1}`,
        schema: data.inputSchema,
        editable: false,
        deletable: false
      }
      output.add(addOption)
    }
  })
}
const createItem = () => {
  const uid = uuid()
  return {
    key: uid,
    name: ``,
    styleContent: emptyStyle,
    style: {}
  }
}
export default {
  '@inputConnected'({ data, output }, fromPin: any) {
    data.inputSchema = fromPin.schema
    if (!Array.isArray(data.styleList)) {
      data.styleList = []
    }
    if (data.styleList.length < 1) {
      data.styleList.push(createItem())
    }
    updateOutput(data, output)
  },
  ':root': ({ data }: any, cate1: any) => {
    cate1.items = [
      {
        title: '样式列表',
        type: 'array',
        options: {
          getTitle: ({ name }, idx) => {
            return name || `样式${idx + 1}`
          },
          onAdd: createItem,
          items: [
            {
              title: '样式名称',
              type: 'text',
              value: 'name'
            },
            {
              title: '样式名称',
              value: 'styleContent',
              type: 'code',
              options: {
                language: 'css',
                enableFullscreen: false,
                title: '编辑校验规则',
                width: 600,
                minimap: {
                  enabled: false
                },
                babel: true,
                eslint: {
                  parserOptions: {
                    ecmaVersion: '2020',
                    sourceType: 'module'
                  }
                }
              }
            }
          ]
        },
        value: {
          get({ data }: any) {
            return data.styleList || []
          },
          set({ data, output }: any, options: any[]) {
            data.styleList = options
            data.styleList.forEach((item: any) => {
              let val = decodeURIComponent(item.styleContent)
              let changed = false
              if (!val) {
                changed = true
                val = emptyStyle
              }
              if (!/^\s*:root\s*{/.test(val)) {
                changed = true
                val = emptyStyle
              }
              item.style = getStyle(val.trim() || '')
              if (changed) {
                item.styleContent = encodeURIComponent(val)
              }
            })
            updateOutput(data, output)
          }
        }
      }
    ]
  }
}
